package com.itheima.web.controller.store;

import com.itheima.core.BaseServlet;
import com.itheima.domain.store.QuestionItem;
import com.itheima.service.store.QuestionItemService;
import com.itheima.service.store.impl.QuestionItemServiceImpl;
import com.itheima.utils.BeanUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/store/questionItem/*")
public class QuestionItemServlet extends BaseServlet {
    private QuestionItemService questionItemService=new QuestionItemServiceImpl();
    public Object list(HttpServletRequest request, HttpServletResponse response)throws Exception{
        /*1.获取表单数据*/
        String questionId = request.getParameter("questionId");

        /*2.调用service*/
        List<QuestionItem> questionItems = questionItemService.findByQuestionId(questionId);

        /*3.回显数据*/
        request.setAttribute("list",questionItems);
        request.setAttribute("questionId",questionId);
        return "/WEB-INF/pages/store/questionItem/list.jsp";
    }

    public Object saveOrUpdate(HttpServletRequest request, HttpServletResponse response)throws Exception{
        /*1.获取表单数据，选项ID*/
        String questionItemId = request.getParameter("id");

        /*2.判断Id是否为空，从而决定是要保存还是更新*/
        if (StringUtils.isBlank(questionItemId)){//添加
            //获取表单数据
            QuestionItem questionItem = BeanUtil.fillBean(request, QuestionItem.class);

            //调用service
            questionItemService.save(questionItem);
        }else {//修改操作
            //获取表单数据
            QuestionItem questionItem = BeanUtil.fillBean(request, QuestionItem.class);
            questionItem.setId(questionItemId);

            //调用service
            questionItemService.update(questionItem);
        }
        return "/store/questionItem/list";
    }

    public Object toEdit(HttpServletRequest request,HttpServletResponse response)throws Exception{
        String questionId = request.getParameter("questionId");//问题Id
        String id = request.getParameter("id");//选项id
        QuestionItem questionItem = questionItemService.findById(id);

        request.setAttribute("questionId",questionId);
        request.setAttribute("questionItem",questionItem);
        return "/store/questionItem/list";
    }

    public Object delete(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String id = request.getParameter("id");
        questionItemService.deleteById(id);

        String questionId = request.getParameter("questionId");
        return "/store/questionItem/list?questionId="+questionId;
    }
}

